#coding: utf-8
import nltk
import logging


class Chunker:
    """
        Used to chunk tagged tokens to obtain named entities
        to build semantic relationships
    """

    def __init__(self, grammar):
        self.parser = nltk.RegexpParser(grammar)


    def chunk_sentence(self, sentence):
        #log chunker input
        logging.debug('------------========CHUNKER INPUT=======--------------')
        for item in sentence:
            logging.debug(item)


        result = self.parser.parse(sentence)

        #result.draw()


        #log chunker result
        logging.debug('------------========CHUNKER OUTPUT=======--------------')
        logging.debug(traverse(result))

        return result

def traverse(t):
    try:
        t.node
    except AttributeError:
        #that exception means 't' is tuple representing a leaf
        print t,
    else:
        # Now we know that t.node is defined
        print '(', t.node,
        for child in t:
            traverse(child)
        print ')',
